package com.atguigu.spzx.pay.service.impl;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayTradePayRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradePayResponse;
import com.atguigu.spzx.common.exception.GuiguException;
import com.atguigu.spzx.common.result.ResultCodeEnum;
import com.atguigu.spzx.pay.config.AlipayProperties;
import com.atguigu.spzx.pay.entity.PaymentInfo;
import com.atguigu.spzx.pay.service.AlipayService;
import com.atguigu.spzx.pay.service.PaymentInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.HashMap;

/**
 * <p>
 * AliPayServiceImpl
 * </p>
 *
 * @author flyduck
 * @since 2023/11/6
 */
@Service
public class AlipayServiceImpl implements AlipayService {

    @Autowired
    private PaymentInfoService paymentInfoService;
    @Autowired
    private AlipayProperties alipayProperties;
    @Autowired
    private AlipayClient alipayClient;

    /**
     * 支付宝下单
     *
     * @param orderNo
     * @return
     */
    @Override
    public String submitAlipay(String orderNo) {
        // 保存支付记录
        PaymentInfo paymentInfo = paymentInfoService.savePaymentInfo(orderNo);

        //调用支付宝接口
        //构建参数
        AlipayTradePayRequest alipayRequest = new AlipayTradePayRequest();
        alipayRequest.setReturnUrl(alipayProperties.getReturnPaymentUrl());
        alipayRequest.setNotifyUrl(alipayProperties.getNotifyPaymentUrl());
        HashMap<String, Object> map = new HashMap<>();
        map.put("out_trade_no", paymentInfo.getOrderNo());
        map.put("product_code", "QUICK_WAP_WAY");
        //正式环境使用
        //map.put("total_amount",paymentInfo.getAmount());
        //测试环境使用
        map.put("total_amount", new BigDecimal("0.01"));
        map.put("subject", paymentInfo.getContent());
        alipayRequest.setBizContent(JSON.toJSONString(map));
        //调用支付宝接口
        try {
            AlipayTradePayResponse payResponse = alipayClient.pageExecute(alipayRequest);
            if (payResponse.isSuccess()) {
                String form = payResponse.getBody();
                return form;
            } else {
                throw new GuiguException(ResultCodeEnum.DATA_ERROR);
            }
        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }
    }
}
